<template>
  <div class="scene-node">
    <el-form label-position="top" :rules="rules" label-width="80px" :model="formData" ref='nodeForm'>
      <div class="scene-title">
        <span>满足以下</span>
        <ChooseLogic :val.sync="formData.subSceneLogic"/>
        <span>子场景，即场景成立：</span>
      </div>
      <!-- 子场景 -->
      <div class="subscene-group" v-for="(item, index) in formData.subScenes" :key="`scenes${index}`">
        <div class="subscene-title">
          <span>子场景{{ index + 1 }}： 满足以下</span>
          <ChooseLogic :val.sync="item.signalLogic"/>
          <span>信号规则</span>
        </div>
        <!-- 信号列表 -->
        <div class="signal-list">
          <signal-list-item
            v-for="(signalItem, signalItemIndex) in item.signals"
            :key="`scenes${index}signal${signalItemIndex}`"
            :ref="`scenes${index}signal${signalItemIndex}`"
            :signalData="signalItem"
            @change="signalChange($event, signalItem)"
            @delete="removeSignal(item, signalItemIndex)">
          </signal-list-item>
          <el-button v-if="item.signals.length < maxSignal" type="text" class="add-signal" @click="addSignal(item.signals)">
            <i class="el-icon-circle-plus"></i>
            添加信号
          </el-button>
        </div>
        <div class="subscene-group-remove el-icon-close" @click="removeSubscene(formData.subScenes, index)"></div>
      </div>
      <el-button v-if="formData.subScenes.length < maxSubscene" type="text" class="add-scene" @click="addSubscene(formData.subScenes)" >
        <i class="el-icon-circle-plus"></i>
        添加子场景
      </el-button>
      <ContinueJudge :subScenes='formData.subScenes' :form.sync='formData.continuousJudgment' ref='continueJudge'></ContinueJudge>
    </el-form>
  </div>
</template>

<script>
import { deepClone } from '@/utils/helper/jsUtil'
import RuleNodeBaseClass from '@/components/ruleNode/RuleNodeBaseClass'
import SignalListItem from './components/signalListItem.vue'
import ChooseLogic from './components/chooseLogic.vue'
import ContinueJudge from './components/continueJudge.vue'

export default {
  name: 'SceneLibAutoExitNode',
  mixins: [RuleNodeBaseClass],
  components: {
    SignalListItem, ChooseLogic, ContinueJudge
  },
  props: {
  },
  data() {
    return {
      maxSubscene: 10,
      maxSignal: 10,
      formData: {
        subSceneLogic: 'and',
        subScenes: [],
        publishEvent: 'ProductStart',
        continuousJudgment: {
          isContinuousJudge: false,
          duration: undefined,
          keepStrategy: '',
          keepTimes: undefined,
          loopJudgment: true
        }
      },
      rules: {
      }
    }
  },
  mounted() {
  },
  methods: {
    initValue() {
      const initFormData = this.initialForm ? deepClone(this.initialForm) : {}
      Object.assign(this.formData, initFormData)
      this.formData.subScenes = this.formData.subScenes || []
      this.formData.subSceneLogic = this.formData.subSceneLogic || 'and'
      this.formData.continuousJudgment = this.formData.continuousJudgment || { isContinuousJudge: false, loopJudgment: true }
      // 默认创建一条数据
      if (!this.formData.subScenes.length) {
        this.formData.subScenes.push({
          signalLogic: 'and',
          signals: [
            {
              signalGroup: '',
              signalName: '',
              signalKey: '',
              metaModelId: '',
              operator: '',
              value: ''
            }
          ]
        })
      }
    },
    addSignal(data) {
      if (data.length < this.maxSignal) {
        data.push({
          signalGroup: '',
          signalName: '',
          signalKey: '',
          metaModelId: '',
          operator: '',
          value: ''
        })
      }
    },
    addSubscene(data) {
      if (data.length < this.maxSubscene) {
        data.push({
          signalLogic: 'and',
          signals: [
            {
              signalGroup: '',
              signalName: '',
              signalKey: '',
              metaModelId: '',
              operator: '',
              value: ''
            }
          ]
        })
      }
    },
    removeSignal(data, index) {
      if (data.signals.length > 1) {
        data.signals.splice(index, 1)
        const signals = deepClone(data.signals)
        // signals.forEach(signal => { signal.metaModelId = signal.metaModelId[1] })
        data.signals = []
        this.$nextTick(() => { data.signals.push(...signals) })
      }
    },
    removeSubscene(data, index) {
      if (data.length > 1) {
        data.splice(index, 1)
        data.forEach(item => {
          const signals = deepClone(item.signals)
          // signals.forEach(signal => { signal.metaModelId = signal.metaModelId[1] })
          item.signals = []
          this.$nextTick(() => { item.signals = signals })
        })
      }
    },
    signalChange(emitData, signalItem) {
      Object.assign(signalItem, emitData)
    },
    getFormData() {
      const data = deepClone(this.formData)
      data.subScenes.forEach(subSceneItem => {
        subSceneItem.signals.forEach(signalItem => {
          if (signalItem.metaModelId && signalItem.metaModelId.includes('&_&')) { // 选中了车端结构体信号，需要把metaModelId转为后端用的格式
            signalItem.metaModelId = signalItem.signalId
          }
          if (['()', '[]'].includes(signalItem.operator)) {
            // 最小值和最大值调换
            if (signalItem.value - 0 > signalItem.maxValue - 0) {
              const maxValue = signalItem.value
              signalItem.value = signalItem.maxValue
              signalItem.maxValue = maxValue
            }
          }
        })
      })
      return data
    },
    validateForm() {
      let isValid = true
      // 信号表单校验
      this.formData.subScenes.forEach((subSceneItem, index) => {
        subSceneItem.signals.forEach((signalItem, signalItemIndex) => {
          const signal = this.$refs[`scenes${index}signal${signalItemIndex}`]
          signal[0].$refs.signalForm.validate(valid => { (!valid) && (isValid = false) })
        })
      })
      // 持续判断校验
      this.$refs.continueJudge.$refs.nodeForm.validate(valid => { (!valid) && (isValid = false) })
      return isValid
    }
  }
}
</script>

<style lang="scss" scoped>
@import "~@/assets/styles/variables.scss";

.scene-node {
  .el-form{
    overflow: visible;
  }
  .scene-title,
  .subscene-title {
    margin-bottom: 8px;
    font-weight: bold;
  }
  .subscene-group {
    position: relative;
    padding: 16px 16px 10px;
    background: $color-gray;
    margin-bottom: 8px;
    .subscene-group-remove {
      position: absolute;
      top: 0;
      right: 0;
      width: 24px;
      height: 24px;
      line-height: 24px;
      border-radius: 2px;
      background: rgba(0, 0, 0, .3);
      color: #fff;
      font-size: 18px;
      text-align: center;
      cursor: pointer;
    }
  }
  .add-signal,
  .add-scene {
    font-size: 14px;
  }
}
</style>
